package com.dukk.gis.tools;

import org.locationtech.jts.geom.*;
import java.math.BigDecimal;

/**
 * 点坐标工具类
 */
public class PointTool {

    static GeometryFactory geometryFactory = GeoTool.getGeoFactory();


    /**
     * 通过 linkString 设置point的高度
     * @param linkString
     * @param point
     */
    public static double getPointZ(Geometry linkString, Point point) {


        Coordinate[] coordinates = linkString.getCoordinates();


        Coordinate[] lineCoordinate = new Coordinate[2];

        double distance = 0;
        double z = 0;
        for(int i=0; i< coordinates.length;i++){

            int next = i;
            if(i + 1 < coordinates.length){
                next = i+1;
            }

            lineCoordinate[0] = coordinates[i];
            lineCoordinate[1] = coordinates[next];

            LineString lineString = geometryFactory.createLineString(lineCoordinate);

            double pointToLineDistance = point.distance(lineString);
            if(i == 0 || pointToLineDistance < distance){
                distance = pointToLineDistance;

                double z1 = coordinates[i].getZ();
                double z2 = coordinates[next].getZ();

                BigDecimal zb1 = new BigDecimal(z1);
                BigDecimal zb2 = new BigDecimal(z2);

                z =  zb1.add(zb2).divide(new BigDecimal(2)).setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue();
            }

        }

        return z;

    }


    /**
     * 获取平均Z
     * @param geometry
     * @return
     */
    public static double getAvgZ(Geometry geometry){
        Coordinate[] coordinates = geometry.getCoordinates();
        int i=0;
        double totalZ = 0;
        for (;i<coordinates.length;i++){
            totalZ+=coordinates[i].getZ();
        }
        BigDecimal bigDecimal = new BigDecimal(i);//NOSONAR
        BigDecimal bigDecimalTotalZ = new BigDecimal(totalZ);//NOSONAR

        return bigDecimalTotalZ.divide(bigDecimal,BigDecimal.ROUND_HALF_UP).setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue();

    }


}
